<template>
  <!-- 安全责任指标考核记录-新增、编辑上报 -->
  <base-breadcrumb :breadcrumb="!isAudit">
    <template v-slot:content>
      <div class="page-header table-page-search-wrapper">
        <a-card :bordered="false">
          <title-name :title="pageType === 'look' ? '信息详情' : '基本信息'" />
          <a-form-model
            ref="form"
            :model="formInfo"
            :rules="rules"
            hide-required-mark
          >
            <a-row :gutter="24">
              <a-col
                :md="8"
                :sm="8"
              >
                <a-form-model-item
                  label="所属分公司"
                  :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
                  :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
                  prop="branchComId"
                >
                  <SelectSubCompany
                    v-model="formInfo.branchComId"
                    :disabled="isDisabled"
                  />
                </a-form-model-item>
              </a-col>
              <a-col
                :md="8"
                :sm="8"
              >
                <a-form-model-item
                  label="所属项目"
                  :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
                  :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
                  prop="projectId"
                >
                  <SelectProject
                    v-model="formInfo.projectId"
                    :disabled="isDisabled"
                    :isClear="formInfo.id===null"
                    :is-edit="formInfo.id!==null"
                    key-value="branchComId"
                    :form="formInfo"
                    @change="handleProjectChanged"
                  />
                </a-form-model-item>
              </a-col>
              <a-col
                :md="8"
                :sm="8"
              >
                <a-form-model-item
                  label="人员"
                  :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
                  :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
                  prop="assessedEmployeeId"
                >
                  <SelectPersonByProject
                    v-model="formInfo.assessedEmployeeId"
                    :project-id="formInfo.projectId"
                    :disabled="isDisabled"
                    @change="handlePersonChanged"
                    @focus="personSelectLock = false"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>

            <a-row :gutter="24">
              <a-col
                :md="8"
                :sm="8"
              >
                <a-form-model-item
                  label="考核月份"
                  :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
                  :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
                  prop="month"
                >
                  <a-select
                    v-model="formInfo.month"
                    :disabled="isDisabled"
                    placeholder="请选择"
                  >
                    <a-select-option
                      v-for="item in monthList"
                      :key="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-card>
      </div>
    </template>
    <div class="page-body">
      <a-card :borderred="false">
        <title-name title="打分项" />
        <s-table
          ref="table"
          bordered
          size="default"
          row-key="id"
          :columns="columns"
          :data="loadData"
          :alert="true"
          show-size-changer
          show-quick-jumper
          :show-pagination="false"
        >
          <template
            slot="serial"
            slot-scope="text, record, index"
          >
            {{ index + 1 }}
          </template>
          <template
            v-for="code in codeList"
            :slot="code"
            slot-scope="text, record, index"
          >
            <div :key="code">
              <span v-if="pageType === 'look'">{{ text }}</span><BaseInput
                v-else-if="code === '6'"
                v-model="record[getCloumnKey(code)]"
                style="width: 100px"
                @blur="validateExamForm"
              /><BaseTextarea
                v-else
                v-model="record[getCloumnKey(code)]"
              />
            </div>
          </template>
        </s-table>
        <div class="statistics-info">
          <span>总分：{{ targetTotalScore }}</span>
          <span style="margin-left: 100px">检查得分：{{ shouldTotalScore }}</span>
          <span
            style="margin-left: 25px"
          >换算百分制得分：<span style="font-weight: bold">{{ shouldTotalScorePercent }}</span></span>
        </div>
      </a-card>
      <div
        v-if="pageType !== 'look'"
        class="tool-btns"
      >
        <a-button
          v-if="formInfo.auditStatus === 'DRAFT' && pageType !== 'add'"
          type="danger"
          :loading="loading.DELETE"
          @click="handleSave('DELETE')"
        >
          删除草稿
        </a-button>
        <a-button
          v-if="formInfo.auditStatus === 'DRAFT'"
          type="primary"
          :loading="loading.DRAFT"
          @click="handleSave('DRAFT')"
        >
          保存草稿
        </a-button>
        <a-button
          type="primary"
          :loading="loading.SUBMITTED"
          @click="handleSave('SUBMITTED')"
        >
          提交
        </a-button>
        <a-button
          type="primary"
          @click="handleClose"
        >
          关闭
        </a-button>
      </div>
      <div
        v-else
        class="tool-btns"
      >
        <a-button
          v-if="checkVisibleInDetail"
          type="primary"
          @click="handleClose"
        >
          关闭
        </a-button>
      </div>
    </div>
  </base-breadcrumb>
</template>

<script>
import {
  getPersonalExamByOrg,
  getExamFormHeader,
  addExamRecord,
  updateExamRecord,
  deleteExamRecord,
  getRecordDetailByDraft,
  getRecordDetailByAudit,
  confirmExamRecord
} from '@/api/safetySupervision/examRecord.js'
import SelectSubCompany from '@/components/Select/SelectSubCompany.vue'
import SelectProject from '@/components/Select/SelectProject.vue'
import { STable } from '@/components'
import Vue from 'vue'
import SelectPersonByProject from '@/components/Select/SelectPersonByProject'
import { checkVisibleInDetail } from '@/utils/util'
export default {
  name: 'a' + Date.now(),
  components: {
    STable,
    SelectSubCompany,
    SelectProject,
    SelectPersonByProject
  },
  data() {
    return {
      checkVisibleInDetail: checkVisibleInDetail(this),
      codeList: ['5', '6'], // 允许输入编辑的列code值
      personSelectLock: true,
      personList: [],
      confirmInfo: {},
      monthCheckFormId: '', // 月度考核表ID
      loading: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false
      },
      tableList: [],
      monthList: [],
      disabled: {
        basicInfo: false
      },
      formInfo: {
        id:null,
        auditStatus: 'DRAFT',
        assessedEmployeeId: '', // 被考核人员ID
        branchComId: '',
        projectId: '',
        month: '',
        deptId: '',
        jobId: ''
      },
      rules: {
        branchComId: [{ required: true, message: '请选择', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择', trigger: 'change' }],
        deptId: [{ required: true, message: '请选择', trigger: 'change' }],
        jobId: [{ required: true, message: '请选择', trigger: 'change' }],
        assessedEmployeeId: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      columns: [],
      queryParam: {},
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return new Promise((resolve, reject) => {
          resolve({
            data: this.tableList
          })
        })
      }
    }
  },
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },

  computed: {
    pageType() {
      return this.$route.query.pageType || 'look'
    },
    isDisabled() {
      return this.$route.query.pageType === 'look' || this.isManager || this.isAudit
    },
    isManager() {
      // finalId存在时，则进行到项目经理审批的阶段
      const { finalId } = this.$route.query
      return !!finalId
    },
    // 应得分统计
    targetTotalScore() {
      return this.getTotalScore('3')
    },
    // 实得分统计
    shouldTotalScore() {
      return this.getTotalScore('6')
    },
    // 实得分统计的百分制
    shouldTotalScorePercent() {
      const result = (this.shouldTotalScore / this.targetTotalScore) * 100
      return Number.isFinite(result) ? `${result.toFixed(1)}` : '0'
    }
  },
  created() {
    this.initPage()
    this.getDetail()
  },
  methods: {
    getTotalScore(code) {
      const dataIndex = this.getCloumnKey(code)
      if (!dataIndex) return 0
      return this.tableList.reduce((pre, cur) => {
        return pre + (Number.isFinite(Number(cur[dataIndex])) ? Number(cur[dataIndex]) : 0)
      }, 0)
    },
    getCloumnKey(code) {
      const targetData = this.columns.find((item) => item.code === code)
      return (targetData && targetData.dataIndex) || ''
    },
    handleProjectChanged() {
      this.formInfo.assessedEmployeeId = ''
    },
    async getDetail() {
      const { id, finalId, auditStatus } = this.$route.query
      if (!id && !finalId) return
      const params = {
        id: finalId ? finalId : id
      }
      const fn = this.isManager ? getRecordDetailByAudit : getRecordDetailByDraft
      const [err, res] = await fn(params)
      if (!err) {
        this.formInfo = {
          ...this.formInfo,
          ...res.data
        }
        if (this.isManager) {
          this.confirmInfo = {
            preCheckId: res.data.preCheck.id
          }
        }
        this.getExamFormHeader() // 获取表头
        this.tableList = res.data.safetyCheckMap
        this.$refs.table.refresh(true)
      }
    },
    validateForm() {
      let flag = false
      this.$refs.form.validate((valid) => {
        flag = valid
      })
      return flag
    },
    validateExamForm() {
      // 考核项目
      const examNameKey = this.getCloumnKey('1')
      // 实得分
      const realScoreKey = this.getCloumnKey('6')
      // 应得分
      const shouldScoreKey = this.getCloumnKey('3')
      for (let i = 0; i < this.tableList.length; i++) {
        const target = this.tableList[i]
        if (target[realScoreKey] === '' || target[realScoreKey] === null) {
          this.$message.error(`${target[examNameKey]}：请填写实得分`)
          return false
        }
        if (!Number.isFinite(Number(target[realScoreKey]))) {
          this.$message.error(`${target[examNameKey]}：实得分必须为正确的数字`)
          return false
        }
        if (Number(target[realScoreKey]) > Number(target[shouldScoreKey])) {
          this.$message.error(`${target[examNameKey]}：实得分不能大于应得分`)
          return false
        }
      }
      return true
    },
    // 处理增、删、改操作
    async handleSave(status) {
      if (!this.isManager && status !== 'DELETE' && !this.validateForm()) return
      if (status === 'SUBMITTED' && this.tableList.length === 0) {
        this.$message.error('没有考核内容，无法提交')
        return
      }
      if (!this.validateExamForm()) return
      if (this.loading[status]) return
      this.loading[status] = true
      const params = {
        ...this.formInfo,
        auditStatus: status,
        id: this.$route.query.id || void 0,
        safetyCheckMap: this.tableList,
        monthCheckFormId: this.monthCheckFormId,
        preCheckId: this.monthCheckFormId,
        checkDate: this.formInfo.month,
        ...this.confirmInfo,
        totalScore: this.shouldTotalScore,
        totalScorePercent: this.shouldTotalScorePercent
        // assessedEmployeeId: '154b4b1aa7614ea2b28304f5f16c6ee2'
      }
      const { pageType } = this.$route.query
      let fn = null
      if (this.isManager) {
        // 如果是项目经理，那么调用确认接口
        fn = confirmExamRecord
      } else {
        fn = pageType === 'edit' ? updateExamRecord : addExamRecord
      }
      const map = {
        DELETE: deleteExamRecord,
        DRAFT: fn,
        SUBMITTED: fn
      }
      const [err, res] = await map[status](params)
      if (!err) {
        this.$message.success('成功')
        this.handleClose()
      }
      this.loading[status] = false
    },
    async getExamFormHeader() {
      const params = {
        employeeId: this.formInfo.assessedEmployeeId,
        projectId: this.formInfo.projectId
      }
      const [err, res] = await getExamFormHeader(params)
      if (!err) {
        const list = (res.data || []).map((item) => {
          const data = {
            ...item,
            title: item.name,
            dataIndex: item.id
          }
          const codeList = this.codeList
          if (codeList.includes(item.code)) {
            data.scopedSlots = { customRender: item.code }
          }
          // 实际情况的列宽
          if (item.code === '5') {
            data.width = '400px'
          }
          return { ...data }
        })
        list.unshift({
          title: '序号',
          dataIndex: 'serial',
          width: 65,
          scopedSlots: { customRender: 'serial' }
        })
        this.columns = list
      }
    },
    // 考核表内容
    async getPersonalExamByOrg(callback) {
      const params = {
        employeeId: this.formInfo.assessedEmployeeId,
        projectId: this.formInfo.projectId
      }
      const [err, res] = await getPersonalExamByOrg(params)
      if (!err) {
        this.monthCheckFormId = res.data.id
        this.tableList = res.data.safetyCheckMap || []
        this.$refs.table.refresh(true)
        callback && callback()
      }
    },
    // 人员变动
    handlePersonChanged(id) {
      if (!id || this.personSelectLock) return
      // 需要在考核表内容返回后，再获取表头（因为如果没有考核表，后台会重新生成，如果表头提前获取，则会发生数据不匹配的问题，因此需要在回调里调用）
      this.getPersonalExamByOrg(() => {
        this.getExamFormHeader()
      })
    },
    initPage() {
      const now = new Date()
      const year = now.getFullYear()
      const month = now.getMonth() + 1
      this.monthList = Array.from({ length: 12 }, (k, i) => {
        const loopMonth = i + 1
        return {
          label: `${year}年${loopMonth}月`,
          value: `${year}-${loopMonth < 10 ? '0' + loopMonth : loopMonth}`
        }
      })
      this.formInfo.month = `${year}-${month < 10 ? '0' + month : month}`
      const { auditStatus } = this.$route.query
      if (auditStatus) {
        this.formInfo.auditStatus = auditStatus
      }
    },
    handleClose() {
      if (this.isAudit) {
        window.close()
      } else {
        this.$multiTab.close(this.$route.fullpath)
      }
    }
  }
}
</script>

<style lang="less" scoped>
@deep: ~'>>>';
.statistics-info {
  display: block;
  padding: 5px 0;
  text-align: right;
  font-size: 16px;
}
.tool-btns {
  display: flex;
  justify-content: flex-end;
  @{deep} .ant-btn + .ant-btn {
    margin-left: 12px;
  }
}
</style>
